package com.hongxun.design.acceptance.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.acceptance.mode.problemExist;
import com.hongxun.design.acceptance.mode.problemExistPhoto;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.BigImageActivity;
import com.hongxun.design.activitys.RegeditActivity;
import com.hongxun.design.bean.CreateDistanceBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.MClickListener;
import com.hongxun.design.mytools.CheckUtil;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.myiossheet.ActionSheet;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.StringUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.camerautil.CameraUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.FileUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by cqcqwu on 验收记录详情
 */

public class AcceptDetailActivity extends BaseActivity {
    private String title = null;
    private ArrayList<String> poplist = null;
    private CreateDistanceBean bean;
    private Handler handler;
    private TextView textRes, findtime, dealtime, tvTitle, tvType, tvYs;
    private EditText etPro, etFinder, etAdvice, etRes, etDealer;
    private LinearLayout layPhoto;
    private problemExist exit;
    private List<problemExistPhoto> photos;
    private List<problemExist> existList;
    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_acceptdetail);
        this.activity = this;
        initHander();
        findBar();
        initDate();
    }

    private void initDate() {
        //添加验收标志
        if (StringUtil.getNull(exit.getResults()).equals("已验收")) tvYs.setText(exit.getResults());
        tvTitle.setText(title);
        tvType.setText("存在问题：" + StringUtil.getNull(exit.getBigType()) + "-" + StringUtil.getNull(exit.getSmallType()));
        etPro.setText(StringUtil.getNull(exit.getExistDescribe()));
        etFinder.setText(StringUtil.getNull(exit.getFinder()));
        findtime.setText(TimeUtil.longToStr(exit.getFindTime()));
        etAdvice.setText(StringUtil.getNull(exit.getAdvice()));
        textRes.setText(StringUtil.getNull(exit.getResults()));
        etRes.setText(StringUtil.getNull(exit.getNote()));
        etDealer.setText(StringUtil.getNull(exit.getHandler()));
        dealtime.setText(TimeUtil.longToStr(exit.getHandleTime()));
        if (exit.getHandleTime() == 0) dealtime.setText("");

        existList = DataFactory.getExPro(getApplicationContext());
        if (existList == null) existList = new ArrayList<>();
        photos = DataFactory.getExProPh(getApplicationContext());
        layPhoto.removeAllViews();
        if (photos != null) {
            for (problemExistPhoto photo : photos) {
                if (exit.getGuid().equals(StringUtil.getNull(photo.getProblemExistGuid()))) {
                    setPhotoView(photo);
                }
            }
        } else {
            photos = new ArrayList<>();
        }
    }

    //照片item
    private void setPhotoView(final problemExistPhoto photo) {
        View addView = LayoutInflater.from(this).inflate(R.layout.view_layitem_photo, null);
        ViewHolder holder = new ViewHolder(addView);
        if (new File(photo.getPhoneUrls()).exists()) {
            holder.ivYs.setImageBitmap(BitmapFactory.decodeFile(photo.getPhoneUrls()));
        } else {
            String aNull = StringUtil.getNull(photo.getComputerUrls());
            if (!aNull.contains(".jpg") || !aNull.contains("\\/")) {
                holder.ivYs.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.zhanweidianshe));
            } else {
                holder.ivYs.setImageURI(UriUtil.getUri(aNull));
            }
        }
        holder.ivYs.setOnClickListener(new MClickListener(0, StringUtil.getNull(photo.getPhoneUrls())) {
            @Override
            public void onClick(View view, int position, Object msg) {
                Intent intent = new Intent(activity, BigImageActivity.class);
                intent.putExtra(MString.PATH, msg + "");
                startActivity(intent);
            }
        });
        holder.ivYsDel.setOnClickListener(new MClickListener(0, addView) {
            @Override
            public void onClick(View view, int position, Object msg) {
                for (problemExistPhoto existPhoto : photos) {
                    if (photo.getGuid().equals(existPhoto.getGuid())) {
                        layPhoto.removeView((View) msg);
                        if (StringUtil.getNull(existPhoto.getStates()).equals("新增")) {
                            photos.remove(existPhoto);
                        } else {
                            existPhoto.setStates("删除");
                        }
                        break;
                    }
                }
            }
        });
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(240, -2);
        layPhoto.addView(addView, 0, params);
    }

    private void initHander() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        textRes.setText(poplist.get((Integer) msg.obj));
                        break;
                    case 2:
                        findtime.setText(bean.getValue());
                        break;
                    case 3:
                        dealtime.setText(bean.getValue());
                        break;
                }
            }
        };
    }

    private void findBar() {
        this.poplist = DataUtil.getResPopItem();
        this.bean = new CreateDistanceBean();
        this.title = getIntent().getStringExtra("0");
        tvTitle = (TextView) findViewById(R.id.tv_title);

        textRes = (TextView) findViewById(R.id.tv_result);
        findtime = (TextView) findViewById(R.id.tv_findtime);
        dealtime = (TextView) findViewById(R.id.tv_dealtime);
        tvType = (TextView) findViewById(R.id.tv_type);
        tvYs = (TextView) findViewById(R.id.tv_title_r);

        etPro = (EditText) findViewById(R.id.et_problem);
        etFinder = (EditText) findViewById(R.id.et_finder);
        etAdvice = (EditText) findViewById(R.id.et_advice);
        etRes = (EditText) findViewById(R.id.et_result);
        etDealer = (EditText) findViewById(R.id.et_dealer);

        layPhoto = (LinearLayout) findViewById(R.id.layout_photos);

        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.setpoint_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("保存", View.VISIBLE, R.color.bar_right, ListenerSet.back,
                getIntent().getStringExtra("1"), R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveDate();
            }
        });

        if (getIntent().hasExtra("2")) {
            exit = (problemExist) getIntent().getSerializableExtra("2");
        } else {
            exit = new problemExist();
            exit.setGuid(UUID.randomUUID().toString());
            exit.setBigType("其他");
            exit.setSmallType("其他");
            exit.setFinder(MyApp.userInfo.getUsername());
            exit.setHandler("");
            exit.setResults("未处理");
            exit.setAccepter(MyApp.userInfo.getUsername());
            String pointID = MyApp.currExploration.getExploration_id();
            if (TextUtils.isEmpty(pointID)) {
                pointID = MyApp.currExploration.getUuid();//离线时适用
            }
            exit.setPointId(pointID);
            exit.setProjectId(MyApp.currProject.getStage_id());
            exit.setStates("新增");
            exit.setFindTime(System.currentTimeMillis());
            exit.setHandleTime(0);
        }
    }

    //保存按钮：照片 、数据
    private void saveDate() {
        String tv1 = String.valueOf(textRes.getText().toString().trim());
        String tv2 = String.valueOf(findtime.getText().toString().trim());
        String tv3 = String.valueOf(dealtime.getText().toString().trim());
        String et1 = String.valueOf(etPro.getText().toString().trim());
        String et2 = String.valueOf(etFinder.getText().toString().trim());
        String et3 = String.valueOf(etAdvice.getText().toString().trim());
        String et4 = String.valueOf(etRes.getText().toString().trim());
        String et5 = String.valueOf(etDealer.getText().toString().trim());
        exit.setResults(tv1);
        exit.setFindTime(TimeUtil.stringTolong(tv2, "yyyy-MM-dd"));
        long time = 0;
        if (!TextUtils.isEmpty(tv3) && !tv3.equals("0"))
            time = TimeUtil.stringTolong(tv3, "yyyy-MM-dd");
        exit.setHandleTime(time);
        exit.setExistDescribe(et1);
        exit.setFinder(et2);
        exit.setAdvice(et3);
        exit.setNote(et4);
        exit.setHandler(et5);
        if (StringUtil.getNull(exit.getStates()).equals(MString.xmYTB)) exit.setStates("修改");
        if (getIntent().hasExtra("2")) {
            for (problemExist exist : existList) {
                if (exit.getGuid().equals(exist.getGuid())) {
                    existList.remove(exist);
                    existList.add(0, exit);
                    break;
                }
            }
        } else {
            existList.add(0, exit);
        }
        DataFactory.saveExPro(getApplicationContext(), FastJsonUtil.beanToJson(existList));
        DataFactory.saveExProPh(getApplicationContext(), FastJsonUtil.beanToJson(photos));
        finish();
    }

    private void openSheet(Activity activity, final String... titles) {
        activity.setTheme(R.style.ActionSheetStyleIOS7);
        ActionSheet menuView = new ActionSheet(activity);
        menuView.setCancelButtonTitle("取消");// before add items
        menuView.addItems(titles);
        menuView.setItemClickListener(new ActionSheet.MenuItemClickListener() {
            @Override
            public void onItemClick(int itemPosition) {
                if (itemPosition == 0) return;
                if (itemPosition == 1) {
                    CameraUtil.pickPhoto(RegeditActivity.Code_Select);//相册
                } else {
                    CameraUtil.openCamera(RegeditActivity.Code_Pick);//拍照
                }
            }
        });
        menuView.setCancelableOnTouchMenuOutside(true);
        menuView.showMenu();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String path = "";
            fundtime = System.currentTimeMillis();
            switch (requestCode) {
                case 1:
                    path = Environment.getExternalStorageDirectory() + "/" + Constant.TMP_PATH;
                    break;
                case 2:
                    path = CheckUtil.getFilePath(this, data.getData());
                    break;
            }
            savePhoto(path);
        }
    }

    private long fundtime = 0;

    //验收文件夹下
    private void savePhoto(String path) {
        //照片保存
        String p = MyApp.File.getCachaPhotoPath_YH() + "/" + fundtime + ".jpg";
        FileUtil.deleteFile(p);
        CameraUtil.saveToString(path, p);
        //存储数据
        problemExistPhoto existPhoto = new problemExistPhoto();
        existPhoto.setGuid(UUID.randomUUID().toString());
        existPhoto.setStates("新增");
        existPhoto.setPhoneUrls(p);
        existPhoto.setPhotoName(fundtime + ".jpg");
        existPhoto.setProblemExistGuid(exit.getGuid());
        existPhoto.setComputerUrls("");
        photos.add(0, existPhoto);
        //展示照片
        setPhotoView(existPhoto);
    }

    //拍照
    public void setTakePhoto(View view) {
        openSheet(this, "选择方式", "相册", "拍照");
    }

    //设置处理结果
    public void setDealResult(View view) {
        PopwindowUtil.popChoice_JG_file(this, view, poplist, handler, 1);
    }

    //设置日期
    public void setTime(View view) {
        int dex = -1;
        switch (view.getId()) {
            case R.id.tv_findtime:
                dex = 2;
                break;
            case R.id.tv_dealtime:
                dex = 3;
                break;
        }
        PopwindowUtil.timeChoice(this, bean, view, handler, dex);
    }

    class ViewHolder {
        private ImageView ivYs;
        private ImageView ivYsDel;

        ViewHolder(View view) {
            ivYs = (ImageView) view.findViewById(R.id.iv_ys);
            ivYsDel = (ImageView) view.findViewById(R.id.iv_ys_del);
        }
    }
}
